package com.core.framework.struts2.web;

import java.beans.Introspector;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
 * 基础事件类
 * @author 刘涛
 * @since Jun 8, 2012
 */
public class BaseAction  extends ActionSupport {
	 /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected static org.slf4j.Logger logger     = org.slf4j.LoggerFactory.getLogger(BaseAction.class);
    protected Logger                  log        = Logger.getLogger(this.getClass());
    protected Gson gosn = new Gson();
	private ActionContext context = ActionContext.getContext();    
	protected HttpServletRequest request  = ServletActionContext.getRequest();
	protected HttpServletResponse response  = ServletActionContext.getResponse();
	/**
	 * 获取一个参数值
	 * @param key
	 * @return
	 */
	protected Object getParameter(Object key)
	{
		if(context.getParameters()!=null)
				return context.getParameters().get(key);
		return null;	
	}
	/**
	 * 获取一个参数集合
	 * @return
	 */
	protected Map<String,Object> getParameters()
	{
		return context.getParameters();
	}
	/**
	 * 获取一个Session 结合
	 * @return
	 */
	protected Map<String,Object> getSessionMap()
	{
		return context.getSession();
	}
	protected <T> T getInstance(Class<T> type)
	{
		return context.getInstance(type);
	}
    private <T> T getBean(String name, Class<T> requiredType) {    
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(
        		ServletActionContext.getServletContext());
        return ctx.getBean(name, requiredType);    
    } 
    protected <T> T getBean(Class<T> requiredType) {        
    		  String shortClassName = ClassUtils.getShortName(requiredType);       
    		  String beanName = Introspector.decapitalize(shortClassName);          
    		  return getBean(beanName, requiredType);    
    }
	protected void writeResponse(String content) {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = null;
	  	try {
			writer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		writer.print(content);
		writer.flush();
		writer.close();		
	}	
}
